package TCPThread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpThreadEchoClient {
    private String serverIp;
    private int serverPort;
    private Socket socket = null;

    public TcpThreadEchoClient(String serverIp,int severPort) throws IOException {
        this.serverIp = serverIp;
        this.serverPort = severPort;
        socket = new Socket(serverIp,serverPort);
    }

    public void start() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            while(true) {
                // 1. 从键盘上读取用户输入的内容 并构造请求
                System.out.print("->");
                Scanner sc = new Scanner(System.in);
                String request = sc.next();
                if(request.equals("exit")){
                    return;
                }
                // 2. 把这个请求发送给服务端
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                printWriter.flush();
                // 3. 从服务器读取响应并解析
                Scanner respScanner = new Scanner(inputStream);
                String response = respScanner.next();
                // 4. 把结果显示到屏幕上
                String log = String.format("req: %s; resp: %s",request,response);
                System.out.println(log);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpThreadEchoClient client = new TcpThreadEchoClient("127.0.0.1",9090);
        client.start();
    }
}
